package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.dao.*;
import com.sc.nft.dto.*;
import com.sc.nft.entity.*;
import com.sc.nft.entity.vo.*;
import com.sc.nft.entity.vo.ecology.*;
import com.sc.nft.enums.EcologyRewardsType;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.mapper.*;
import com.sc.nft.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class AdminEcologyHatchConfServiceImpl implements AdminEcologyHatchConfService {

    private final EcologyHatchConfDao ecologyHatchConfDao;
    private final EcologyHatchRewardsConfDao ecologyHatchRewardsConfDao;
    private final StaticDataDao staticDataDao;
    private final UserEcologyHatchRecordsDao userEcologyHatchRecordsDao;
    private final DigitalCollectionDao digitalCollectionDao;
    private final UserEcologyExpenditureRecordDao userEcologyExpenditureRecordDao;
    private final UserEcologyCastRecordsDao userEcologyCastRecordsDao;
    private final UserEcologyHatchRewardsRecordsDao userEcologyHatchRewardsRecordsDao;
    private final EcologyHatchCollecionShareProfitConfDao ecologyHatchCollecionShareProfitConfDao;
    private final UserRelevanceDao userRelevanceDao;
    private final UserInfoDao userInfoDao;
    private final UserCreatorInfoDao userCreatorInfoDao;
    private final UserEcologyCollectionRecordsDao userEcologyCollectionRecordsDao;
    private final EcologyHatchExchangeConfDao ecologyHatchExchangeConfDao;
    private final UserEcologyCastRecordsMapper userEcologyCastRecordsMapper;
    private final UserEcologyHatchRecordsMapper userEcologyHatchRecordsMapper;
    private final UserCollectionMapper userCollectionMapper;
    private final UserEquityPropsMapper userEquityPropsMapper;
    private final UserPredictEcologyHatchRewardsRecordsMapper userPredictEcologyHatchRewardsRecordsMapper;
    private final EcologyPointsDao ecologyPointsDao;
    private final EcologyCollectionShareProfitConfService ecologyCollectionShareProfitConfService;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSmeltingConf(EcologyHatchConf ecologyHatchConf) {

        if(ecologyHatchConf.getDestroyCount().intValue() >0){
            Assert.isTrue(ecologyHatchConf.getDestroyCount().intValue() <= ecologyHatchConf.getExpendCount().intValue(),()-> new GlobalRunTimeException("回收数量不能大于消耗数量"));
        }

        if(ObjectUtil.isNull(ecologyHatchConf.getId())){ //插入

            DigitalCollection collection = digitalCollectionDao.getById(ecologyHatchConf.getCollectionId());
            Assert.notNull(collection,()-> new GlobalRunTimeException("数字收藏品不存在"));

            Assert.isTrue(ecologyHatchConfDao.getIsExistByCollectionId(collection.getId()),()-> new GlobalRunTimeException("生态熔炼配置已经存在"));
            ecologyHatchConf.setCollectionName(collection.getFirstTitle());
            ecologyHatchConf.setCollectionImage(collection.getCreationContent());
            ecologyHatchConf.setDaoId(collection.getUserCreatorId());
            ecologyHatchConf.insert();
        }else{
            EcologyHatchConf byId = ecologyHatchConfDao.getById(ecologyHatchConf.getId());
            Assert.notNull(byId,()-> new GlobalRunTimeException("生态熔炼配置不存在"));
            Assert.isFalse(byId.getStatus(),()-> new GlobalRunTimeException("生态熔炼配置已经启用，不可修改"));
            Assert.isTrue(ecologyHatchConfDao.updateSmeltingConf(ecologyHatchConf),()-> new GlobalRunTimeException("生态熔炼配置更新失败"));
        }
    }

    @Override
    public IPage<AdminSmeltingPageVO> getSmeltingPage(String collectionName, Integer pageNo, Integer pageSize) {
        IPage<AdminSmeltingPageVO> smeltingPage = ecologyHatchConfDao.getSmeltingPage(collectionName, pageNo, pageSize);
        List<AdminSmeltingPageVO> records = smeltingPage.getRecords();
        for (AdminSmeltingPageVO record : records) {
            EcologyHatchExchangeConf oneByEcologyHatchId = ecologyHatchExchangeConfDao.getOneByEcologyHatchId(record.getId());
            if (Objects.nonNull(oneByEcologyHatchId)){
                record.setEcologyHatchExchangeConfId(oneByEcologyHatchId.getId());
            }
        }
        return smeltingPage;
    }

    @Override
    public AdminSmeltingDetailsVO getSmeltingDetails(Long id) {
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(id);
        Assert.notNull(ecologyHatchConf,()-> new GlobalRunTimeException("生态熔炼配置不存在"));
        AdminSmeltingDetailsVO adminSmeltingDetailsVO = BeanUtil.copyProperties(ecologyHatchConf, AdminSmeltingDetailsVO.class);
        EcologyHatchCountVO ecologyHatchCount = findEcologyHatchCount(ecologyHatchConf.getId());
        adminSmeltingDetailsVO.setRemainderHatchCount(ecologyHatchCount.getEcologyHatchCount());
        if (ObjectUtil.isNotNull(ecologyHatchConf.getEcologyPointsId())){
            EcologyPoints ecologyPoints = ecologyPointsDao.getById(ecologyHatchConf.getEcologyPointsId());
//            Assert.notNull(ecologyPoints,()-> new GlobalRunTimeException("积分数据异常"));
            if (Objects.nonNull(ecologyPoints)) {
                adminSmeltingDetailsVO.setEcologyPointsName(ecologyPoints.getPointsName());
            }

        }
        return adminSmeltingDetailsVO;
    }

    @Override
    public void delRewardsById(Long id) {
        EcologyHatchRewardsConf ecologyHatchRewardsConf = ecologyHatchRewardsConfDao.getById(id);
        Assert.notNull(ecologyHatchRewardsConf,()-> new GlobalRunTimeException("生态熔炼奖励配置不存在"));
        Assert.isTrue(ecologyHatchRewardsConfDao.delRewardsById(id),()-> new GlobalRunTimeException("删除生态熔炼奖励配置更新失败"));
    }

    @Override
    public void updateSmeltinStatusgById(Long id, Boolean status) {
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(id);
        Assert.notNull(ecologyHatchConf,()-> new GlobalRunTimeException("生态熔炼配置不存在"));


        //判断分成配置是否配置
        Assert.isTrue(ecologyCollectionShareProfitConfService.getCountByConfId(ecologyHatchConf.getId()),()-> new GlobalRunTimeException("生态熔炼配置分成配置未配置"));

        Assert.isTrue(ecologyHatchConfDao.updateSmeltinStatusgById(id,status),()-> new GlobalRunTimeException("生态熔炼配置状态更新失败"));
    }

    @Override
    public void updateSmeltingSortById(Long id, Long sort) {
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(id);
        Assert.notNull(ecologyHatchConf,()-> new GlobalRunTimeException("生态熔炼配置不存在"));

        Assert.isTrue(ecologyHatchConfDao.updateSmeltingSortById(id,sort),()-> new GlobalRunTimeException("生态熔炼配置排序更新失败"));

    }

    @Override
    public List<AdminSmeltingImageVO> getSmeltingImage() {
        return staticDataDao.getListByType();
    }

    @Override
    public void updateSmeltingImage(String type, String image) {
        StaticData staticData = staticDataDao.getByType(type);
        Assert.notNull(staticData,()-> new GlobalRunTimeException("生态熔炼配置图片不存在"));
        Assert.isTrue(staticDataDao.updateStaticData(type,image),()-> new GlobalRunTimeException("生态熔炼配置图片更新失败"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delConfById(Long id) {
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(id);
        Assert.notNull(ecologyHatchConf,()-> new GlobalRunTimeException("生态熔炼配置不存在"));
        Integer statusCount = userEcologyHatchRecordsDao.getStatusCountByEcologyHatchId(id);
        Assert.isFalse(statusCount > 0,()-> new GlobalRunTimeException("生态熔炼配置已经被使用，不可删除"));

        Assert.isTrue(ecologyHatchConfDao.delConfById(id),()-> new GlobalRunTimeException("删除生态熔炼配置更新失败"));
        Assert.isTrue(ecologyHatchRewardsConfDao.delRewardsByEcologyHatchId(id),()-> new GlobalRunTimeException("删除生态熔炼配置奖励配置更新失败"));
    }

    @Override
    public SelectDataByTimeVO selectDataByTime(Date startTime, Date endTime) {
        SelectDataByTimeVO selectDataByTimeVO = new SelectDataByTimeVO();
        selectDataByTimeVO.setPutIntoFuel(userEcologyHatchRecordsDao.getPutIntoFuelByStartTimeAndEndTime(startTime,endTime));
        selectDataByTimeVO.setFuelRelease(userEcologyExpenditureRecordDao.getFuelReleaseByStartTimeAndEndTime(startTime,endTime));
        selectDataByTimeVO.setFoundryFuelConsumption(userEcologyCastRecordsDao.getFoundryFuelConsumptionByStartTimeAndEndTime(startTime,endTime));
        return selectDataByTimeVO;
    }

    @Override
    public Page<AdminUserEcologyHatchRcordsVO> userRecords(Long daoUserId,Long daoId,String collectionName, String userTel, String startTime, String endTime, Integer pageNo, Integer pageSize,String methodName) {
        DigitalCollection digitalCollection = digitalCollectionDao.getByFirstTitle(collectionName);
        Assert.notNull(digitalCollection,()-> new GlobalRunTimeException("未找到藏品"));
        Page<AdminUserEcologyHatchRcordsVO> adminUserEcologyHatchRcordsVOPage = userEcologyHatchRecordsDao.userRecords(daoUserId, daoId, digitalCollection.getId(), userTel, startTime, endTime, pageNo, pageSize,methodName);
        List<AdminUserEcologyHatchRcordsVO> records = adminUserEcologyHatchRcordsVOPage.getRecords();
        for (AdminUserEcologyHatchRcordsVO adminMetaUserEcologyHatchRcordsList : records) {
            List<UserEcologyCollectionRecordsVO> userEcologyCollectionRecordsVOS = userEcologyCollectionRecords(adminMetaUserEcologyHatchRcordsList.getId());
            StringBuffer ecologyDetail = new StringBuffer();
            for (UserEcologyCollectionRecordsVO userEcologyCollectionRecordsVO : userEcologyCollectionRecordsVOS) {
                ecologyDetail = ecologyDetail.append(userEcologyCollectionRecordsVO.getCollectionName()).append("x")
                        .append(userEcologyCollectionRecordsVO.getCollectionCount()).append(",");
            }
            if (ecologyDetail.charAt(ecologyDetail.length() - 1) == ',') {
                ecologyDetail.setLength(ecologyDetail.length() - 1); // 移除末尾的逗号
            }
            adminMetaUserEcologyHatchRcordsList.setEcologyDetail(ecologyDetail.toString());
        }
        return adminUserEcologyHatchRcordsVOPage;

    }

    @Override
    public Page<AdminMetaUserEcologyHatchRcordsVO> adminUserRecords(String collectionName, String userTel, String startTime, String endTime, Integer pageNo, Integer pageSize,String methodName) {


        Page<AdminMetaUserEcologyHatchRcordsVO> adminMetaUserEcologyHatchRcordsVOPage = userEcologyHatchRecordsDao.adminUserRecords(collectionName, userTel, startTime, endTime, pageNo, pageSize, methodName);
        List<AdminMetaUserEcologyHatchRcordsVO> records = adminMetaUserEcologyHatchRcordsVOPage.getRecords();
        for (AdminMetaUserEcologyHatchRcordsVO adminMetaUserEcologyHatchRcordsList : records) {
            List<UserEcologyCollectionRecordsVO> userEcologyCollectionRecordsVOS = userEcologyCollectionRecords(adminMetaUserEcologyHatchRcordsList.getId());
            StringBuffer ecologyDetail = new StringBuffer();
            for (UserEcologyCollectionRecordsVO userEcologyCollectionRecordsVO : userEcologyCollectionRecordsVOS) {
                ecologyDetail = ecologyDetail.append(userEcologyCollectionRecordsVO.getCollectionName()).append("x")
                        .append(userEcologyCollectionRecordsVO.getCollectionCount()).append(",");
            }
            if (ecologyDetail.charAt(ecologyDetail.length() - 1) == ',') {
                ecologyDetail.setLength(ecologyDetail.length() - 1); // 移除末尾的逗号
            }
            adminMetaUserEcologyHatchRcordsList.setEcologyDetail(ecologyDetail.toString());
        }
        return adminMetaUserEcologyHatchRcordsVOPage;
    }

    @Override
    public List<AdminUserEcologyHatchRcordsDetailsVO> userRecordsDetails(Long id) {
        return userEcologyHatchRecordsDao.userRecordsDetails(id);
    }

    @Override
    public List<UserEcologyCollectionRecordsVO> userEcologyCollectionRecords(Long id) {
        return userEcologyCollectionRecordsDao.getList(null, id);
    }

    @Override
    public Page<AdminPageUserRewardsRecordsVO> getPageUserRecordsRecords(Long id,Date startTime, Date endTime, Integer pageNo, Integer pageSize) {
        return userEcologyHatchRewardsRecordsDao.getPageUserRecordsRecords(id,startTime,endTime,pageNo,pageSize);
    }

    @Override
    public List<AdminUserEcologyHatchRcordsVO> userRecordsExport(Long daoId, String collectionName, String userTel, String startTime, String endTime) {
        return userEcologyHatchRecordsDao.userRecordsExport(daoId,collectionName,userTel,startTime,endTime);
    }

    @Override
    public AdminTeamHatchDataVO getPageTeamHatchData(Long daoUserId, Long collectionId, String userTel,Date startTime,  Date endTime) {
        UserInfo user = userInfoDao.getOneByUserTel(userTel);
        Assert.notNull(user,()-> new GlobalRunTimeException("用户不存在"));
        if(user.getId().intValue() != daoUserId.intValue()){
            Assert.isTrue(userRelevanceDao.getIsExistByUserIdAndRelevanceId(daoUserId,user.getId()),()-> new GlobalRunTimeException("用户不在团队内"));
        }

        AdminTeamHatchDataVO adminTeamHatchDataVO = userEcologyHatchRecordsDao.getPageTeamHatchData(daoUserId, collectionId, user.getId(), startTime, endTime);
        adminTeamHatchDataVO.setNickName(user.getNickName());
        adminTeamHatchDataVO.setUserTel(user.getUserTel());
        return adminTeamHatchDataVO;
    }

    /**
     * 熔炼剩余份数
     * @param ecologyHatchId
     * @return
     */
    @Override
    public EcologyHatchCountVO findEcologyHatchCount(Long ecologyHatchId){
        EcologyHatchCountVO ecologyHatchCountVO = new EcologyHatchCountVO();
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(ecologyHatchId);
        Assert.notNull(ecologyHatchConf, () -> new GlobalRunTimeException("熔炼配置不存在"));
        // 获取已熔炼数量
        Integer hatchCountByEcologyHatchId = userEcologyHatchRecordsDao.getHatchCountByEcologyHatchId(ecologyHatchConf.getId());
        //熔炼总份数 - 已熔炼份数 = 剩余熔炼份数
        int ecologyHatchCount = ecologyHatchConf.getTotalHatchCount() - hatchCountByEcologyHatchId;
        if (0 >= ecologyHatchCount){
            ecologyHatchCount = 0;
        }
        ecologyHatchCountVO.setEcologyHatchCount(ecologyHatchCount);
        return ecologyHatchCountVO;
    }

    @Override
    public List<EcologyCollectionCountVO> ecologyCollectionCount(Long daoId) {
        return userEcologyCastRecordsMapper.ecologyCollectionCount(daoId);
    }

    @Override
    public List<EcologySmeltVO> ecologySmeltCount(Long daoId, Date startTime, Date endTime) {
        return userEcologyHatchRecordsDao.ecologySmeltCount(daoId,startTime,endTime);
    }

    @Override
    public List<EcologyTeamDataVO> ecologySmeltTeam(Long daoId, String phoneNo) {
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(daoId);
        UserInfo userInfo = userInfoDao.getOneByUserTel(phoneNo);
        if(ObjectUtil.isNull(userInfo)){
            return Collections.emptyList();
        }
        if(userCreatorInfo.getUserId().longValue()==userInfo.getId().longValue()||userRelevanceDao.getIsExistByUserIdAndRelevanceId(userCreatorInfo.getUserId(),userInfo.getId())){
            List<DigitalCollection> ecologyCollectionLists = digitalCollectionDao.getEcologyCollectionByUserCreatorId(userCreatorInfo.getId());
            List<EcologyTeamDataVO> result = Lists.newArrayList();
            for (DigitalCollection ecologyCollection : ecologyCollectionLists) {
                EcologyTeamDataVO ecologyTeamDataVO = new EcologyTeamDataVO();
                ecologyTeamDataVO.setFirstTitle(ecologyCollection.getFirstTitle());
                ecologyTeamDataVO.setSumSmeltCount(userEcologyHatchRecordsMapper.getUnderSumSmeltCount(userInfo.getId(),ecologyCollection.getId(),null));
                ecologyTeamDataVO.setInSmeltCount(userEcologyHatchRecordsMapper.getUnderSumSmeltCount(userInfo.getId(),ecologyCollection.getId(),1  ));

                ecologyTeamDataVO.setHoldCount(userCollectionMapper.getUnderHoldCount(userInfo.getId(),ecologyCollection.getId()));
                EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getOneByCollectionId(ecologyCollection.getId());
                if(ObjectUtil.isNotNull(ecologyHatchConf)){
                    ecologyTeamDataVO.setSumProduceCount(userPredictEcologyHatchRewardsRecordsMapper.getUnderPropsProduceCount(userInfo.getId(),ecologyHatchConf.getId(),true));
                    ecologyTeamDataVO.setSumWaitProduceCount(userPredictEcologyHatchRewardsRecordsMapper.getUnderPropsProduceCount(userInfo.getId(),ecologyHatchConf.getId(),false));
                    List<Long> listByEcologyHatchIds = ecologyHatchRewardsConfDao.getPropsIdsByEcologyHatchId(ecologyHatchConf.getId());
                    if(CollUtil.isNotEmpty(listByEcologyHatchIds)){
                        ecologyTeamDataVO.setPropsHoldCount(userEquityPropsMapper.getUnderHoldCount(userInfo.getId(),listByEcologyHatchIds));
                    }else{
                        ecologyTeamDataVO.setPropsHoldCount(0L);
                    }
                }else{
                    ecologyTeamDataVO.setSumProduceCount(0L);
                    ecologyTeamDataVO.setSumWaitProduceCount(0L);
                    ecologyTeamDataVO.setPropsHoldCount(0L);
                }

                result.add(ecologyTeamDataVO);
            }
            return result;
        }
        return Collections.emptyList();
    }

}
